package com.revenant.driver.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nanchen.compresshelper.CompressHelper;
import com.revenant.driver.App;
import com.revenant.driver.R;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.ShipperBean.FileUploadBean;
import com.revenant.driver.bean.ShipperBean.PersonalDetailBean;
import com.revenant.driver.utils.ActivityUtils;
import com.revenant.driver.utils.GlideEngine;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.revenant.driver.bean.Message.Driver_RenZheng_5;
import static com.revenant.driver.bean.Message.Driver_RenZheng_6;
import static com.revenant.driver.bean.Message.Driver_RenZheng_7;
import static com.revenant.driver.bean.Message.Driver_RenZheng_8;
import static com.revenant.driver.utils.Constants.Driver_YanZheng;
import static com.revenant.driver.utils.Constants.Get_personal_info;
import static com.revenant.driver.utils.Constants.Name_header_token;
import static com.revenant.driver.utils.Constants.UploadFile;
import static com.revenant.driver.utils.Constants.UploadIdCard;

public class DriverRenZhengTwoActivity extends BaseActivity {
    @BindView(R.id.edit_number)
    EditText editNumber;
    @BindView(R.id.upload_text_type)
    TextView uploadTextType;
    @BindView(R.id.upload_second_title)
    TextView uploadSecondTitle;
    @BindView(R.id.upload_photo)
    ImageView uploadPhoto;
    @BindView(R.id.upload_type)
    Button uploadType;
    private String uploadurltwo = "";
    private String uploadurlone = "";
    private Context context;
    private List<LocalMedia> selectList = new ArrayList<>();
    private String Name_header;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_driver_two;
    }

    @Override
    public void initView() {
        setcenterTitle("完善司机信息");
        context = this;
        Bundle bundle = this.getIntent().getExtras();
        uploadurlone = bundle.getString("upload_type_fileurl");
        Name_header = Utils.get64String() + "_" + SPUtils.getUsermobile(context) + "_" + "0";

    }

    @Override
    public void initData() {

    }

    @Override
    public void leftbarclick() {
        super.leftbarclick();
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.upload_photo, R.id.upload_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.upload_photo:
                showBottomSheetDialog(DriverRenZhengTwoActivity.this);
//                PictureSelector.create(this)
//                        .openGallery(PictureMimeType.ofImage())
//                        .maxSelectNum(1)
//                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
//                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.upload_type:
                if (uploadurltwo.isEmpty()) {
                    showToast("请选择图片");
                } else if (editNumber.getText().toString().trim().isEmpty()) {
                    showToast("输入从业资格证号码");
                } else if (!uploadurlone.isEmpty()) {
                    uploadId(uploadurlone, uploadurltwo, editNumber.getText().toString());
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    selectList = PictureSelector.obtainMultipleResult(data);

                    for (LocalMedia media : selectList) {
                        if (!selectList.isEmpty()) {
                            String url = media.getPath().startsWith("content://") ? media.getAndroidQToPath() : media.getPath();
                            uploadAvatar(url);
                        }
                    }
                    break;
            }
        }
    }

    private void uploadAvatar(final String path) {
        File file = new File(path);
        File newfile = CompressHelper.getDefault(context).compressToFile(file);

        OkGo.<String>post(UploadFile)
                .tag(this)
                .isMultipart(true)

                .params("file", newfile)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                      if (response.code()==200){
                          FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                          if (fileUploadBean.getCode().equals("0")) {
                              uploadurltwo = fileUploadBean.getData().getUrl();
                              Glide.with(context).load(fileUploadBean.getData().getUrl()).centerCrop().
                                      into(uploadPhoto);
                          } else {
                              showToast(fileUploadBean.getMsg());
                          }
                      }else {
                          showToast(response.message());
                      }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("上传失败");
                        LogUtils.d("失败是" + response.message());
                    }
                });
    }

    private void uploadId(String fileone, String filetwo, String qualificationCode) {
        showDig();

        OkGo.<String>post(Driver_YanZheng)
                .headers(Name_header_token, Name_header)
                .params("driverUrl", fileone)
                .params("qualificationUrl", filetwo)
                .params("accountId", SPUtils.getAccounId(context))
                .params("qualificationCode", qualificationCode)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                        if (fileUploadBean.getCode().equals("0")) {
                            getpseronal();
                        } else {
                            showToast(fileUploadBean.getMsg());
                            dismissDig();
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.d("失败是" + response.message());
                        dismissDig();
                    }
                });

    }

    private void getpseronal() {

        OkGo.<String>get(Get_personal_info)

                .params("id", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("AAAA" + response.body());
                        PersonalDetailBean g = GsonUtil.parseJsonWithGson(response.body(), PersonalDetailBean.class);
                        if (g.getCode().equals("0")) {
                            dismissDig();

                            App applicationContext = (App) getApplicationContext();
                            applicationContext.setUserStatus(Integer.valueOf(g.getData().getStatus()));
                            int userStatus = applicationContext.getUserStatus();
                            switch (userStatus) {
                                case 5:
                                    showToast(Driver_RenZheng_5);
                                    startActivity(DriverMineActivity.class);
                                    finish();
                                    break;
                                case 6:
                                    showToast(Driver_RenZheng_6);
//                                    startActivity(DriverRenZhengOneActivity.class);
                                    startActivity(NewImproveDriverInfoaActivity.class);
                                    finish();
                                    break;
                                case 7:
                                    showToast(Driver_RenZheng_7);
                                    startActivity(DriverMineActivity.class);
                                    finish();
                                    break;
                                case 8:
                                    showToast(Driver_RenZheng_8);
                                    startActivity(NewImproveDriverInfoaActivity.class);
                                    finish();
                                    break;
                                default:
                            }
//                            if (g.getData().getStatus().equals("0")) {
//                                finish();
//                                showToast("您的身份认证未通过，请重新认证");
//                                startActivity(DriverRenZhengOneActivity.class);
//                            } else {
//                                finish();
//                                SPUtils.setUserAuthentication(context, String.valueOf(g.getData().getStatus()));
//                                ActivityUtils.removeAllActivity();
//                                showToast("您的身份认证通过");
//                                startActivity(DriverMineActivity.class);
//                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }
}
